import SparkMD5 from "spark-md5";
// import useUsersStore from "@/store/useUsersStore";
// worker中无法获取window对象，所以无法使用sesionStorage，自然，需要携带权限的请求也无法使用
// import { uploadSlice, mergeSlice } from "@/api/upload";

self.onmessage = function ({ data: { file, chunksize = 20 * 1024 * 1024 } }) {
  console.log("worker file", file);
  const types = ["mp4", "avi", "mov", "wmv", "mkv", "flv", "rmvb"];
  if (types.includes(file.name.split(".")[1])) {
    const fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = function (e) {
      const buffer = e.target.result;
      const spark = new SparkMD5.ArrayBuffer();
      spark.append(buffer);
      const hash = spark.end();
      // console.log("uploadSlice", uploadSlice);
      const chunks = arrange(file, chunksize);
      self.postMessage({ hash, chunks });
    };
  }
};


function arrange(file, chunksize = 20 * 1024 * 1024) {
  const maxNum = Math.ceil(file.size / chunksize);
  const chunks = [];
  for (let i = 0; i < maxNum; i++) {
    const start = i * chunksize;
    const end = Math.min(file.size, start + chunksize);
    const blob = file.slice(start, end);
    chunks.push(blob);
  }
  console.log("chunks", chunks);
  return chunks;
}
